import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:permission_handler/permission_handler.dart';

class BluetoothClientPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BluetoothClientState();
  }
}

class _BluetoothClientState extends State<BluetoothClientPage> {
  FlutterBlue _flutterBlue;

  @override
  void initState() {
    super.initState();
    _flutterBlue = FlutterBlue.instance;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('lottery'),
      ),
      body: _body(),
    );
  }

  _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          children: [
            OutlineButton(
              child: Text("扫描"),
              onPressed: _startScan,
            ),
            OutlineButton(
              child: Text("连接"),
              onPressed: () {},
            ),
            OutlineButton(
              child: Text("断开"),
              onPressed: () {
                _flutterBlue.stopScan();
              },
            ),
          ],
        ),
      ],
    );
  }

  _startScan() {
    _flutterBlue.startScan(timeout: Duration(seconds: 4));
    _flutterBlue.scanResults.listen((event) {
      event.forEach((element) {
        print(" name=${element.device.name},rssi=${element.rssi}");
      });
    });
  }
}
